<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>音乐实验管理</title>
    <style>
        :root {
            --primary-color: #4a90e2;
            --hover-color: #357abd;
            --background: #f8f9fa;
        }

        body {
            background: var(--background);
            font-family: 'Segoe UI', system-ui;
            background-image: url("{{ url_for('static', filename='images/bg2.2.png') }}");
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
            background-attachment: fixed;
        }

        .manager-container {
            max-width: 800px;
            margin: 2rem auto;
            padding: 2rem;
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        h2 {
            color: #2c3e50;
            font-size: 2rem;
            margin-bottom: 1.5rem;
            border-bottom: 2px solid var(--primary-color);
            padding-bottom: 0.5rem;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin: 1.5rem 0;
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }

        th {
            background: var(--primary-color);
            color: white;
            font-weight: 500;
            padding: 1rem;
        }

        td {
            padding: 1rem;
            border-bottom: 1px solid #e0e0e0;
        }

        tr:last-child td {
            border-bottom: none;
        }

        tr:hover td {
            background-color: #f5f5f5;
        }

        .play-btn {
            width: 120px;
            min-width: 120px;
            max-width: 120px;
            justify-content: center;
            white-space: nowrap;
            background: linear-gradient(145deg, var(--primary-color), var(--hover-color));
            border: none;
            color: white;
            padding: 8px 16px;
            border-radius: 25px;
            cursor: pointer;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s ease, background 0.3s;
        }

        .logout-link {
            text-align: center;
        }

        .play-btn.active {
            background: linear-gradient(145deg, #ffa800, #ff9002);
            box-shadow: 0 2px 10px rgba(102, 168, 255, 0.4);
        }

        .play-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
        }

        .play-btn::before {
            content: '▶';
            font-size: 0.9em;
        }

        #usernameInput {
            padding: 10px 16px;
            border: 1px solid #ddd;
            border-radius: 25px;
            width: 300px;
            margin-right: 1rem;
            transition: border-color 0.3s;
        }

        #usernameInput:focus {
            outline: none;
            border-color: var(--primary-color);
        }

        #experimentButton {
            background: linear-gradient(145deg, #34c759, #2ca84d);
            color: white;
            padding: 12px 24px;
            border-radius: 25px;
            border: none;
            cursor: pointer;
            transition: transform 0.2s;
        }

        #status {
            height: 30px;
            background: #ccffcc;
            border-radius: 4px;
            align-items: center;
            text-align: center;
            margin-top: 10px;
            margin-bottom: 10px;
        }

        form[action="beginExpriment"] {
            min-height: 150px;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 8px;
            margin-bottom: 20px;
        }

        .progress-container {
            width: 200px;
            height: 4px;
            background: #eee;
            border-radius: 2px;
            margin-top: 8px;
            cursor: pointer;
            position: relative;
        }

        .progress-bar {
            height: 100%;
            background: var(--primary-color);
            border-radius: 2px;
            width: 0%;
            position: relative;
        }

        .progress-time {
            position: absolute;
            right: -80px;
            top: -4px;
            font-size: 12px;
            color: #666;
            white-space: nowrap;
        }

        td[align="center"] {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 8px;
        }
    </style>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.4.1/socket.io.js"></script>
</head>

<body>
    <div class="manager-container">
        <h2>管理页面</h2>
        <form method="post" action="beginExpriment">
            <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #2c3e50;">当前实验者ID：</label>
            <div style="display: flex; align-items: center; gap: 1rem;">
                <input type="text" name="username" id="usernameInput" placeholder="输入用户名" required>
                <button type="button" id="experimentButton">开始实验，并生成结果</button>
            </div>
            <div id="status"></div>
        </form>
        <h3>疗愈音乐列表</h3>
        <table>
            <thead>
                <tr>
                    <th>序号</th>
                    <th>文件名</th>
                    <th align="center">操作</th>
                </tr>
            </thead>
            <tbody>
                {% for filename in music_files %}
                <tr>
                    <td>{{ loop.index }}</td>
                    <td>{{ filename }}</td>
                    <td align="center">
                        <button class="play-btn">播放</button>
                        <div class="progress-container">
                            <div class="progress-bar"></div>
                            <div class="progress-time">0:00 / 0:00</div>
                        </div>
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
        <div class="logout-link">
            <a href="{{ url_for('logout') }}">注销</a>
        </div>
    </div>

    <script>
        const socket = io();
        const experimentButton = document.getElementById('experimentButton');
        const statusDiv = document.getElementById('status');
        const usernameInput = document.getElementById('usernameInput');
        let isExperimenting = false;
        let currentAudio = null;
        let lastPlayButton = null;

        // 用户名存储
        const storedUsername = localStorage.getItem('username');
        if (storedUsername) {
            usernameInput.value = storedUsername;
        }
        usernameInput.addEventListener('input', function () {
            localStorage.setItem('username', this.value);
        });

        // 实验控制
        experimentButton.addEventListener('click', function () {
            if (!isExperimenting) {
                isExperimenting = true;
                experimentButton.textContent = '结束实验';
                socket.emit('start_experiment', { username: usernameInput.value });
            } else {
                isExperimenting = false;
                experimentButton.textContent = '开始实验，并生成结果';
                socket.emit('end_experiment', { username: usernameInput.value });
            }
        });

        // 状态显示
        socket.on('experiment_status', function (data) {
            if (data.status === 'started') {
                animateStatus();
            } else if (data.status === 'ended') {
                statusDiv.textContent = '结束实验';
            }
        });

        // 工具函数
        function animateStatus() {
            let dots = '.';
            const intervalId = setInterval(() => {
                if (isExperimenting) {
                    dots = dots.length > 15 ? '.' : dots + '...';
                    statusDiv.textContent = `${dots}`;
                } else {
                    clearInterval(intervalId);
                    statusDiv.textContent = '';
                }
            }, 500);
        }

        // 添加音乐播放状态管理
        let audioElement = null;
        let curPlayButton = null;

        // 格式化时间函数
        function formatTime(seconds) {
            const minutes = Math.floor(seconds / 60);
            const remainingSeconds = Math.floor(seconds % 60);
            return `${minutes}:${remainingSeconds < 10 ? '0' + remainingSeconds : remainingSeconds}`;
        }

        // 更新进度条和时间显示
        function updateProgress() {
            if (audioElement) {
                const progressBar = curPlayButton.nextElementSibling.querySelector('.progress-bar');
                const progressTime = curPlayButton.nextElementSibling.querySelector('.progress-time');
                const duration = audioElement.duration;
                const currentTime = audioElement.currentTime;
                const progress = (currentTime / duration) * 100;
                progressBar.style.width = `${progress}%`;
                progressTime.textContent = `${formatTime(currentTime)} / ${formatTime(duration)}`;
            }
        }

        // 播放控制事件监听
        socket.on('start_playback', function (data) {
            if (audioElement) {
                audioElement.pause();
            }
            audioElement = new Audio(`/static/music/${data.filename}`);
            audioElement.play();
            audioElement.addEventListener('timeupdate', updateProgress);

            if (curPlayButton) {
                curPlayButton.classList.add('active');
                curPlayButton.textContent = '播放中';
            }
        });

        socket.on('pause_playback', function () {
            if (audioElement) {
                audioElement.pause();
            }
        });

        socket.on('stop_playback', function () {
            if (audioElement) {
                audioElement.pause();
                audioElement.currentTime = 0;
                audioElement.removeEventListener('timeupdate', updateProgress);
            }
        });

        // 修改播放按钮点击事件
        document.querySelectorAll('.play-btn').forEach(button => {
            button.addEventListener('click', function () {
                const filename = this.parentElement.previousElementSibling.textContent;
                if (curPlayButton == null) {
                    curPlayButton = this;
                    curPlayButton.textContent = '播放中...';
                    curPlayButton.classList.add('active');
                    socket.emit('play_music', { filename: filename });
                    return;
                }

                if (curPlayButton == this) {
                    curPlayButton.textContent = '播放';
                    curPlayButton.classList.remove('active');

                    // 停止当前音乐播放进度条
                    if (audioElement && curPlayButton && curPlayButton.nextElementSibling) {
                        const progressBar = curPlayButton.nextElementSibling.querySelector('.progress-bar');
                        const progressTime = curPlayButton.nextElementSibling.querySelector('.progress-time');
                        const duration = audioElement.duration;
                        const currentTime = 0;
                        const progress = (0 / duration) * 100;
                        progressBar.style.width = `${progress}%`;
                        progressTime.textContent = `${formatTime(currentTime)} / ${formatTime(duration)}`;
                    }

                    curPlayButton = null;
                    socket.emit('stop_music');
                } else {
                    curPlayButton.textContent = '播放';
                    curPlayButton.classList.remove('active');
                    // 停止当前音乐播放进度条
                    if (audioElement && curPlayButton && curPlayButton.nextElementSibling) {
                        const progressBar = curPlayButton.nextElementSibling.querySelector('.progress-bar');
                        const progressTime = curPlayButton.nextElementSibling.querySelector('.progress-time');
                        const duration = audioElement.duration;
                        const currentTime = 0;
                        const progress = (0 / duration) * 100;
                        progressBar.style.width = `${progress}%`;
                        progressTime.textContent = `${formatTime(currentTime)} / ${formatTime(duration)}`;
                    }
                    socket.emit('stop_music');

                    curPlayButton = this;
                    curPlayButton.textContent = '播放中...';
                    curPlayButton.classList.add('active');
                    socket.emit('play_music', { filename: filename });
                }
            });
        });
    </script>
</body>

</html>